package com.china08.yxyapi.api.manage.tec.teaching.continuedu.mytask;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.continuedu.YxyContinueduStatisticsSchoolTask;
import com.china08.yxyapi.entity.db.continuedu.YxyContinueduTask;
import com.china08.yxyapi.entity.mg.continuedu.YxyContinueduStatisticsUserTask;
import com.china08.yxyapi.entity.mg.continuedu.YxyContinueduUserTask;
import com.china08.yxyapi.entity.mg.continuedu.YxyContinueduUserTaskLesson;
import com.china08.yxyapi.entity.mg.continuedu.YxyContinueduUserTaskLessonItem;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.db.continuedu.YxyContinueduStatisticsSchoolTaskRepository;
import com.china08.yxyapi.repository.db.continuedu.YxyContinueduTaskRepository;
import com.china08.yxyapi.repository.mg.continuedu.YxyContinueduStatisticsUserTaskRepository;
import com.china08.yxyapi.repository.mg.continuedu.YxyContinueduUserTaskLessonItemRepository;
import com.china08.yxyapi.repository.mg.continuedu.YxyContinueduUserTaskLessonRepository;
import com.china08.yxyapi.repository.mg.continuedu.YxyContinueduUserTaskRepository;

/**
 * 
 * @annotation: 继续教育-用户完成课时更新相关数据
 * @author: yaoguanglin
 */
@CrossOrigin
@RestController
public class YxyMyTaskFinishUpdController extends YxyApiBaseController {

    private static final Logger LOGGER = Logger.getLogger(YxyMyTaskFinishUpdController.class);

    @Autowired
    private YxyContinueduUserTaskLessonItemRepository userLessonItemRepository;

    @Autowired
    private YxyContinueduUserTaskLessonRepository yxyContinueduUserTaskLessonRepository;

    @Autowired
    private YxyContinueduStatisticsUserTaskRepository yxyContinueduStatisticsUserTaskRepository;

    @Autowired
    private YxyContinueduTaskRepository yxyContinueduTaskRepository;

    @Autowired
    private YxyContinueduStatisticsSchoolTaskRepository statisticsSchoolTaskRepository;

    @Autowired
    private YxyContinueduUserTaskRepository yxyContinueduUserTaskRepository;

    @RequestMapping(value = "/api_yw/manage/tec/teaching/continuedu/mytask/status/upd", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespModel process(HttpServletRequest request, HttpServletResponse response,
            @RequestBody(required = false) ReqModel reqModel) {

        String userId = getProfile(request, response).getId();
        String itemId = reqModel.itemId;
        String schoolId = getProfile(request, response).getSchoolId();
        RespModel model = new RespModel();
        try {
            // 查询课时信息
            YxyContinueduUserTaskLessonItem userItem = userLessonItemRepository.findById(itemId);
            // 查询任务信息
            YxyContinueduUserTask userTask = yxyContinueduUserTaskRepository.findByUserIdAndTaskId(userId,
                    userItem.getTaskId());
            String taskId = userTask.getTaskId();
            // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            // Date date = new Date();
            // String string = sdf.format(date) + " 23:59:59";
            // SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd
            // HH:mm:ss");
            // date = sdf1.parse(string);
            // 修改课时状态为已学习
            userItem.setStatus(1);
            userLessonItemRepository.save(userItem);

            // 修改课时所属课程进度
            String lessonId = userId + "_" + userItem.getTaskId() + "_" + userItem.getLessonId();
            YxyContinueduUserTaskLesson userTaskLesson = yxyContinueduUserTaskLessonRepository.findById(lessonId);

            // 查询该课程下已完成的课时数量以及总课时数量
            Integer finishCount = userLessonItemRepository.countByTaskIdAndLessonIdAndStatusAndUserId(taskId,
                    userItem.getLessonId(), 1, userId);
            // 已完成的课时数量
            // 总的课时数量
            Integer total = userLessonItemRepository.countByTaskIdAndLessonIdAndUserId(taskId, userItem.getLessonId(),
                    userId);

            double f = (float) finishCount / total;
            BigDecimal b = new BigDecimal(f);
            double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() * 100;

            // 为课程进度重新赋值
            userTaskLesson.setProgress(f1);
            yxyContinueduUserTaskLessonRepository.save(userTaskLesson);

            // 修改该课程所属任务进度
            // 查询该任务下已完成的课时以及所有课时 (任务进度是根据该任务下已完成的课时数量/ 所有课时数量)
            // 已完成课时
            Integer finishLessonCount = userLessonItemRepository.countByUserIdAndTaskIdAndStatus(userId,
                    userItem.getTaskId(), 1);

            // 所有课时
            Integer totalLessonCount = userLessonItemRepository.countByUserIdAndTaskId(userId, userItem.getTaskId());

            double fTask = (float) finishLessonCount / totalLessonCount;
            BigDecimal bTask = new BigDecimal(fTask);
            double fTask1 = bTask.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() * 100;
            userTask.setProgress(fTask1);
            if (fTask1 == 100) {
                userTask.setStatus(1);
            }
            yxyContinueduUserTaskRepository.save(userTask);

            // 如果完成了任务,修改任务表数据以及本校任务数据
            if (fTask1 == 100) {
                // 统计我的任务完成数据
                YxyContinueduStatisticsUserTask continueduStatisticsUserTask = yxyContinueduStatisticsUserTaskRepository
                        .findById(userId);
                // 根据课程ID 统计本次课程数量
                Long lessonCount = yxyContinueduUserTaskLessonRepository.countByTaskId(taskId);
                // 查询本次任务分数
                YxyContinueduTask continueduTask = yxyContinueduTaskRepository.findById(taskId);
                if (continueduStatisticsUserTask == null) {
                    YxyContinueduStatisticsUserTask userTask2 = new YxyContinueduStatisticsUserTask();
                    userTask2.setFinishCount(1l);
                    userTask2.setId(userId);
                    userTask2.setLessonCount(lessonCount);
                    userTask2.setMyScore(Long.valueOf(continueduTask.getScore()));
                    userTask2.setUserId(userId);
                    yxyContinueduStatisticsUserTaskRepository.save(userTask2);
                } else {
                    continueduStatisticsUserTask.setFinishCount(continueduStatisticsUserTask.getFinishCount() + 1l);
                    continueduStatisticsUserTask
                            .setLessonCount(continueduStatisticsUserTask.getLessonCount() + lessonCount);
                    continueduStatisticsUserTask
                            .setMyScore(continueduStatisticsUserTask.getMyScore() + continueduTask.getScore());
                    yxyContinueduStatisticsUserTaskRepository.save(continueduStatisticsUserTask);
                }
                // 更新任务表和统计表
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("schoolId", schoolId);
                map.put("taskId", userItem.getTaskId());
                // RabbitMqSendUtil.finishTaskStatis(map);
                YxyContinueduStatisticsSchoolTask schoolTask = statisticsSchoolTaskRepository
                        .findBySchoolIdAndTaskId(schoolId, taskId);

                // 更新结业人数
                Long completeCount = schoolTask.getCompleteCount() + 1l;
                schoolTask.setCompleteCount(completeCount);

                Long applyCount = schoolTask.getApplyCount();
                // 更新结业率 保留两位小数
                double rate = (float) completeCount / applyCount;
                BigDecimal b1 = new BigDecimal(rate);
                Double completeRate = b1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() * 100;
                schoolTask.setCompleteRate(completeRate);
                statisticsSchoolTaskRepository.save(schoolTask);

                /**
                 * 更新任务表数据
                 */
                YxyContinueduTask yxyContinueduTask = yxyContinueduTaskRepository.findById(taskId);
                // 更新结业人数
                Long completeCountTask = yxyContinueduTask.getCompleteCount() + 1l;
                yxyContinueduTask.setCompleteCount(completeCountTask);

                Long applyCountTask = yxyContinueduTask.getApplyCount();
                // 更新结业率 保留两位小数
                double rateTask = (float) completeCountTask / applyCountTask;
                BigDecimal bTask1 = new BigDecimal(rateTask);
                Double completeRateTask = bTask1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() * 100;
                yxyContinueduTask.setCompleteRate(completeRateTask);

                yxyContinueduTaskRepository.save(yxyContinueduTask);
            }
            model.setMessage("更新任务进度成功");

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            LOGGER.info("继续教育-----更新任务进度失败");
        }

        return model;
    }

    protected static class ReqModel extends YxyApiReqModel {
        // 课时ID
        public String itemId;
    }

    protected static class RespModel extends YxyApiRespModel {

    }

}
